import xlrd
import requests
import json

#excelPath = "C:\\work\\code\\etag\\5 eStation\\51 Server\\Inuit\\package\\Language.xls"
#codePath = "C:\\work\\code\\etag\\5 eStation\\51 Server\\Inuit\Inuit.Framework\\Inuit.Framework.Common\\MsgCode.cs"
#url = "http://localhost:5018/sys/Language/sync2"

excelPath = "Language.xls"
codePath = "..\\Inuit.Framework\\Inuit.Framework.Common\\MsgCode.cs"
url = "http://192.168.4.25:9001/inuit/sys/Language/sync2"


def read_excel(file_path):
    table_data = []
    # 打开 Excel 文件读取数据
    workbook = xlrd.open_workbook(file_path)
    # 获取所有的 Sheet 名称
    all_sheets = workbook.sheet_names()
    for sheet_name in all_sheets:
        # 获取指定 Sheet 工作表内容
        table = workbook.sheet_by_name(sheet_name)
        # 遍历每一行
        if(sheet_name == "sys"):
            table_data[len(table_data):] = processErrorCode(table)
            #table_data.append(processErrorCode(table))
            continue

        #table_data.append(process(sheet_name, table))
        table_data[len(table_data):] = process(sheet_name, table)
        

    return table_data

def processErrorCode(table):
    excel_data = readCode(table)
    writeErrorCode(excel_data)
    return buildErrorData(excel_data)

def readCode(table):
    table_data = []
    headers = []
    # 遍历每一行
    for row_index in range(table.nrows):
        if(row_index == 0):
            headers = table.row_values(rowx=row_index)
            continue

        rowValue = table.row_values(rowx=row_index)
        data = {}
        for header_index in range(len(headers)):
            header = headers[header_index].strip()
            data[header] = rowValue[header_index]
            if isinstance(data[header] , (int, float)):
                data[header] = str(int(data[header])).strip()
            else:
                data[header] = data[header].strip()
        table_data.append(data)
    return table_data

def writeErrorCode(data):
    header = """
    namespace Inuit.Framework.Common;

    /// <summary>
    /// 状态码枚举
    /// </summary>
    public class MsgCode
    {
    """

    bodyHeader = """
        /// <summary>
        /// {classComment}
        /// </summary>
        public enum {className}
        {{
    """
    
    bodyContent = """
            /// <summary>
            /// {zh-CN}
            /// </summary>
            {contentEnum} = {contentValue},
    """
        
    bodyFoot = """
        }
    """
    
    foot = """
    }
    """

    code = header

    key = ""
    for i in range(len(data)):
        if key == data[i]["className"]:
            code += bodyContent.format(**data[i])
        else:
            if key != "":
                code += bodyFoot
            code += bodyHeader.format(**data[i])
            key = data[i]["className"]
            code += bodyContent.format(**data[i])
    code += bodyFoot
    code += foot
    
    f1 = open(codePath, 'w', encoding = 'utf-8')
    f1.write(code)
    f1.close()
    print("生成语言文件成功")

def buildErrorData(data):
    res = []
    for item in data:
        for key in item:
            if key == "classComment":
                continue
            
            if key == "className":
                continue

            if key == "contentEnum":
                continue

            if key == "contentValue":
                continue

            res.append( {
                    "group": "SYS",
                    "code": key,
                    "key": item['contentValue'],
                    "value": item[key]
            })

    return res
    #headers = {'Content-Type': 'application/json'}
    #response = requests.post(url, data=json.dumps(res), headers=headers)
    #print(response.text)


def process(sheetName, table):
    excel_data = readCode(table)
    return buildData(sheetName, excel_data)


def buildData(sheetName, data):
    res = []
    for item in data:
        for key in item:
            if key == "UseInApp":
                continue
            
            if key == "Key":
                continue

            res.append( {
                    "group": sheetName,
                    "code": key,
                    "key": item['Key'],
                    "value": item[key]
            })
    return res


def importData(data):
    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, data=json.dumps(data), headers=headers)
    print(response.text)







excel_data = read_excel(excelPath)
#print(json.dumps(excel_data))


print("导入数据库")
importData(excel_data)



price_str = input("完成")